import fetch from "node-fetch";
import lodash from "lodash";
import fs from "fs";
import path from "path";
import yaml from "yaml";
import { fileURLToPath } from "url";
import { createLogger } from '../modules/Logger.js';

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 配置文件路径
const CONFIG_PATH = path.resolve(__dirname, "../config/woc.yaml");

export class WocPlugin extends plugin {
    constructor() {
        super({
            name: "wocpp",
            dsc: "PP版神秘指令图片获取",
            event: "message",
            priority: 500,
            rule: [
                {
                    reg: "^#?(woc|卧槽)",
                    fnc: "wocHandler",
                    permission: "all"
                },
                {
                    reg: "^#添加woc群白\\s+(\\d+)$",
                    fnc: "addGroupWhite",
                    permission: "master"
                },
                {
                    reg: "^#添加woc机白\\s+(\\d+)$",
                    fnc: "addBotWhite",
                    permission: "master"
                }
            ]
        });
        // 创建日志实例
        this.logger = createLogger(this.name);

        try {
            const configFile = fs.readFileSync(CONFIG_PATH, "utf8");
            this.config = yaml.parse(configFile);
            this.config.whiteListGroups = this.config.whiteListGroups || [];
            this.config.whiteListBots = this.config.whiteListBots || [];
            this.config.cdTime = this.config.cdTime || 60;
        //    this.logger.info("配置文件加载成功");
        } catch (error) {
            this.logger.error(`配置文件加载失败：${error.message}`);
            throw new Error("WOC插件初始化失败");
        }
    }

    async wocHandler() {
        if (!this.e.isGroup) {
            this.e.reply("[安全限制] 请勿私聊使用本指令", true);
            this.logger.error(`拒绝私聊请求 用户：${this.e.user_id}`);
            return false;
        }

        const currentGroup = Number(this.e.group_id);
        const currentBot = Number(this.e.bot.uin);

        if (!this.checkPermission(currentGroup, currentBot)) {
            this.e.reply("为避免扰民特加权限，请联系皮皮开放白名单", true);
            this.logger.error(`权限拒绝 群：${currentGroup} 机器人：${currentBot}`);
            return false;
        }

        const cdKey = `Yz:woc:${currentGroup}`;
        const remainingCD = await this.getRemainingCD(cdKey);

        if (remainingCD > 0) {
            const cdMsg = this.formatCDMessage(remainingCD);
            this.e.reply(`指令冷却中，剩余时间：${cdMsg}`, true);
            this.logger.info(`冷却阻止 群：${currentGroup} 剩余：${remainingCD}s`);
            return false;
        }

        redis.set(cdKey, "1", { EX: this.config.cdTime });
        this.logger.info(`权限通过 群：${currentGroup} 机器人：${currentBot}`);

        await this.executeMainLogic();
    }

    async addGroupWhite() {
        return this.handleWhiteList("whiteListGroups", "群白名单");
    }

    async addBotWhite() {
        return this.handleWhiteList("whiteListBots", "机器人白名单");
    }

    async handleWhiteList(listType, listName) {
        const id = this.e.msg.match(/\d+/)[0];
        if (!id) {
            await this.e.reply(`请输入正确的${listName}ID`);
            return true;
        }

        if (this.config[listType].includes(Number(id))) {
            await this.e.reply(`该ID已在${listName}中`);
            return true;
        }

        this.config[listType].push(Number(id));

        try {
            const yamlStr = yaml.stringify(this.config);
            fs.writeFileSync(CONFIG_PATH, yamlStr, 'utf8');
            await this.e.reply(`${listName}添加成功 ✅`);
            this.logger.info(`${listName}更新: ${id}`);
        } catch (error) {
            this.logger.error(`配置保存失败: ${error.message}`);
            await this.e.reply("配置保存失败，请检查服务器权限");
        }
        return true;
    }

    async getRemainingCD(key) {
        try {
            const ttl = await redis.ttl(key);
            return ttl > 0 ? ttl : 0;
        } catch (error) {
            this.logger.error(`冷却查询失败：${error.message}`);
            return 0;
        }
    }

    formatCDMessage(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins}分${secs.toString().padStart(2, '0')}秒`;
    }

    async executeMainLogic() {
        await this.e.reply("探索神秘空间中...", true);

        try {
            const randomPage = Math.floor(Math.random() * 50) + 1;
            const response = await fetch(`${this.config.apiUrl}${randomPage}`);

            if (!response.ok) throw new Error(`HTTP ${response.status}`);
            const data = await response.json();

            const images = this.extractImages(data);
            if (!images.length) {
                this.e.reply("没有找到任何图片，换个姿势试试吧~", true);
                return;
            }

            const sendImages = lodash.sampleSize(images, this.config.imageLimit);
            await this.sendImages(sendImages);
            this.logger.info(`成功发送 ${sendImages.length} 张图片`);

        } catch (err) {
            this.logger.error(`操作失败：${err.message}`);
            this.e.reply("连接神秘空间失败，请稍后再试", true);
        }
    }

    checkPermission(groupId, botId) {
        return this.config.whiteListGroups.includes(groupId) ||
            this.config.whiteListBots.includes(botId);
    }

    extractImages(data) {
        try {
            const content = lodash.get(data, "[0].content.rendered", "");
            const imgTags = content.match(/<img.*?src="(.*?)"/g) || [];
            return imgTags
              .map(img => img.replace(/.*src="([^"]+).*/, "$1"))
              .filter(url => url.startsWith("http"));
        } catch (error) {
            this.logger.error(`图片解析失败：${error.message}`);
            return [];
        }
    }

    async sendImages(images) {
        try {
            const messages = images.map(url => ({
                message: segment.image(url),
                nickname: this.config.forwardAsBot ? this.e.bot.nickname : this.e.sender.card,
                user_id: this.config.forwardAsBot ? this.e.bot.uin : this.e.user_id
            }));

            const forwardMsg = await Bot.makeForwardMsg(messages);
            await this.e.reply(forwardMsg, false, {
                recallMsg: this.config.deleteMsg
            });
        } catch (error) {
            this.logger.error(`图片发送失败：${error.message}`);
            throw new Error("图片发送过程中出现错误");
        }
    }
}